#include "HttpServer.hpp"

#include <memory>

using namespace std;
using namespace Server;
static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}
std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg;image/jpeg";

    ct += "\r\n";
    return ct;
}

// 1.服务器与网页分离
// 2.url中的/是web根目录，不是linux的根目录
// 3.正确的给客户端返回资源类型，根据后缀辨别
bool Get(const HttpRequst &req, HttpResponse &resp)
{
    if(req.path=="/search")
    {
        //根据提交上来的数据去执行其他任务
        
    }
    cout << "----------------------http start---------------------------" << endl;
    cout << req.inbuffer << endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size <<"字节"<< std::endl;
    cout << "----------------------http end---------------------------" << endl;

    std::string respline = "HTTP/1.0 200 OK\r\n";      // 状态行

    //std::string respline = "HTTP/1.1 307 Temporary Redirect\r\n";//临时重定向
    
    std::string respheader = suffixToDesc(req.suffix); // 根据后缀编写响应报头

    if (req.size > 0)
    {
        respheader += "Content-Length: "; // 正文部分大小
        respheader += std::to_string(req.size);
        respheader+="\r\n";
    }

    //重定向到指定页面
    //respheader += "Location: https://mp.csdn.net/?spm=1030.2200.3001.8539\r\n";
    std::string respblank = "\r\n"; // 空行

    std::string body; // 正文
    body.resize(req.size+1);
    // 根据访问文件路径，读取文件内容放到body里
    if (!Util::readFile(req.path, (char*)body.c_str(),req.size))
    {
        Util::readFile(html_404, (char*)body.c_str(),req.size); // 读不到返回404
    }

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    cout<<"-----------------http response stat-----------"<<endl;
    cout<<resp.outbuffer<<endl;
    cout<<"-----------------http response end-----------"<<endl;
    resp.outbuffer += body;

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t serverport = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, serverport));

    //根据访问path，执行不同的方法-----功能路由
    // httpsvr->registerCb("/",Get);
    // httpsvr->registerCb("/a.py",other);
    httpsvr->InitServer();

    httpsvr->start();

    return 0;
}